<?php
namespace Home\Controller;

class CommonController extends \Think\Controller{
	
    protected $openid;
    protected $customer_id = 1;
    protected $user;
    protected $appid;
    protected $access_token;
    
    public function _initialize(){
        header("Content-Type: text/html; charset=utf-8");
        //获取openid
        //session('openid','');
        if(session('openid')){
            $this->openid = session('openid');
        }else{
        	$this->openid = $this->getAuthOpenid();
        	session('openid',$this->openid);
        }
        $this->user = D('User')->where("openid='{$this->openid}'")->find();
        $this->assign('user',$this->user);
    }
    
    /**
     * 网页授权获取用户信息
     */
    public function getAuthOpenid($is_get_info = true){
    	$appconfig = D('Customer')->where("id='{$this->customer_id}'")->find();
    	if(empty($appconfig['appid']) || empty($appconfig['appsecret'])) return false;
    	if($_REQUEST['code']){

    		$json_result = D('Api')->curl_request("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appconfig['appid']."&secret=".$appconfig['appsecret']."&code=".$_REQUEST['code']."&grant_type=authorization_code");
             die(var_dump($json_result));
    		$result = json_decode($json_result,true);

    		$result['openid'] || $this->error("获取用户信息失败，原因：未关注此公众号，或未知错误");
    		$is_get_info && $this->getAuthInfo($result);
    		return $result['openid'];
    	}else{
    		$redirectUri = urlencode(U('',null,true,true));//openid处理页面(当前页面)
    		header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appconfig['appid']}&redirect_uri=$redirectUri&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
    		exit;
    	}
    }
    
    /**
     * 同步用户信息
     * @param 粉丝 $openid
     * @param 网页授权获取用户信息token $access_token
     */
    public function getAuthInfo($auth_data){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$auth_data['access_token'].'&openid='.$auth_data['openid'].'&lang=zh_CN';
        $jsonStr = D('Api')->curl_request($url);
        $jsonData = json_decode($jsonStr,true);
        $userinfo['customer_id'] = $this->customer_id;
        $userinfo['openid'] = $jsonData['openid'];
        $userinfo['nickname'] = $jsonData['nickname'];
        $userinfo['sex'] = $jsonData['sex'];
        $userinfo['language'] = $jsonData['language'];
        $userinfo['headimgurl'] = $jsonData['headimgurl'];
        $userinfo['province'] = $jsonData['province'];
        $userinfo['city'] = $jsonData['city'];
        $userinfo['country'] = $jsonData['country'];
        if($id = D('User')->where("openid='{$auth_data['openid']}'")->getField('id')){
            D('User')->where("id='$id'")->save($userinfo);
        }else{
            D('User')->add($userinfo);
        }
    }
    protected function ini_wx() {
    	$this->access_token = D('Customer')->getToken($this->customer_id,$this->appid);
    }
    protected function getSignPackage() {
    	$jsapiTicket = $this->getJsApiTicket();
        
    	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    	$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    	$timestamp = time();
    	$nonceStr = $this->createNonceStr();
    
    	// 这里参数的顺序要按照 key 值 ASCII 码升序排序
    	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    
    	$signature = sha1($string);
    
    	$signPackage = array(
    			"appId"     => $this->appid,
    			"nonceStr"  => $nonceStr,
    			"timestamp" => $timestamp,
    			"url"       => $url,
    			"signature" => $signature,
    			"rawString" => $string
    	);
    	return $signPackage;
    }
    
    protected function createNonceStr($length = 16) {
    	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    	$str = "";
    	for ($i = 0; $i < $length; $i++) {
    		$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    	}
    	return $str;
    }
    
    protected function getJsApiTicket() {
    	$this->ini_wx();
    	// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
    	$jsapi_ticket_data = D('Jsapi')->find();

    	if (!$jsapi_ticket_data || $jsapi_ticket_data['expire_time'] < time()) {
            
    		$accessToken = $this->access_token;
            
    		// 如果是企业号用以下 URL 获取 ticket
    		// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
    		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
    		$res = json_decode(curl_request($url));
            $ticket = $res->ticket;
    		if ($ticket) {
    			$data = array();
    			$data['customer_id'] = $this->customer_id;
    			$data['ticket'] = $ticket;
    			$data['expire_time'] = time() + 7000;
                if(!empty($jsapi_ticket_data['id'])){
                    D('Jsapi')->where("id='{$jsapi_ticket_data['id']}'")->save($data);
                }else{
                    D('Jsapi')->add($data);
                }
    		}
    	} else {
    		$ticket = $jsapi_ticket_data['ticket'];
    	}
    	return $ticket;
    }
}